package com.robert.custombehavior.behavior

import android.content.Context
import android.graphics.Rect
import android.support.design.widget.CoordinatorLayout
import android.util.AttributeSet
import android.view.View

import com.robert.custombehavior.R

class HeaderTabViewBehavior : CoordinatorLayout.Behavior<View> {

    private val mHeadRect = Rect()

    constructor() {}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}

    override fun layoutDependsOn(parent: CoordinatorLayout, child: View, dependency: View): Boolean {
        return isDependOn(dependency)
    }

    override fun onDependentViewChanged(parent: CoordinatorLayout, child: View, dependency: View): Boolean {
        child.translationY = dependency.translationY
        return true
    }

    override fun onLayoutChild(parent: CoordinatorLayout, child: View, layoutDirection: Int): Boolean {
        val dependencies = parent.getDependencies(child)
        val dependency = findDependency(dependencies)
        if (dependency != null) {
            mHeadRect.set(dependency.left, dependency.bottom, dependency.right, dependency.bottom + child.measuredHeight)
            child.layout(mHeadRect.left, mHeadRect.top, mHeadRect.right, mHeadRect.bottom)
        }
        return true
    }


    private fun findDependency(views: List<View>): View? {
        var i = 0
        val z = views.size
        while (i < z) {
            val view = views[i]
            if (isDependOn(view))
                return view
            i++
        }
        return null
    }

    private fun isDependOn(dependency: View?): Boolean {
        return dependency != null && dependency.id == R.id.header
    }

    companion object {

        private val TAG = "HeaderTabViewBehavior"
    }

}